#!/bin/bash

# ==============================================================
# 脚本名称: build-push-sealos-isolated.sh
# 作用: 使用临时 BuildDir 隔离环境，构建并推送多架构镜像
# ==============================================================

set -euo pipefail

# --- 1. 变量准备 ---
cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1
# 自动探测: 目录名做版本, 上级目录名做应用名
DEFAULT_VERSION=$(basename "$PWD")
DEFAULT_NAME=$(basename "$(dirname "$PWD")")

if [ -z "${1:-}" ]; then
    echo -e "\033[0;31mError: 请提供 Docker Hub 用户名。\033[0m"
    echo "用法: $0 <hub-user> [image-name] [version]"
    exit 1
fi

HUB_USER="$1"
APP_NAME="${2:-$DEFAULT_NAME}"
VERSION="${3:-$DEFAULT_VERSION}"

# 注册表地址 (Docker Hub)
REGISTRY="docker.io"

# 镜像全名定义
IMAGE_NAME_FULL="${REGISTRY}/${HUB_USER}/${APP_NAME}:${VERSION}"
IMG_AMD64="${IMAGE_NAME_FULL}-amd64"
IMG_ARM64="${IMAGE_NAME_FULL}-arm64"
TARGET_AMD64="docker://${IMG_AMD64}"
TARGET_ARM64="docker://${IMG_ARM64}"
TARGET_FULL="docker://${IMAGE_NAME_FULL}"

# --- 2. 登录 Registry (修正写法) ---
echo -e "\033[1;33m==> [1/4] 登录 $REGISTRY ...\033[0m"
# 如果脚本非交互式运行，请确保密码已通过其他方式传递或已登录
sealos login -u "$HUB_USER" "$REGISTRY"

# --- 函数: 在独立目录中构建并推送 ---
build_image_arch() {
    local ARCH=$1
    local IMG_TAG=$2
    local IMG_DEST=$3
    
    # 定义临时构建目录名称
    local BUILD_DIR=".build-image-${ARCH}"

    echo -e "\033[1;34m--> 处理架构: ${ARCH}\033[0m"
    
    # 1. 清理并创建 builddir
    rm -rf "$BUILD_DIR"
    mkdir -p "$BUILD_DIR"

    # 2. 复制当前目录内容到 builddir (排除 builddir 自身防止递归)
    # 使用 ls -A 列出所有文件(含隐藏文件)，grep 排除构建目录，然后 cp
    echo "    正在复制上下文到 $BUILD_DIR ..."
    ls -A | grep -vE "^(\.build-image-.*)$" | xargs -I {} cp -rf {} "$BUILD_DIR/"

    # 3. 进入 builddir 进行构建
    pushd "$BUILD_DIR" > /dev/null
    
    echo "    开始构建 ($ARCH)..."
    sealos build --platform "linux/${ARCH}" -t "$IMG_TAG" -f ./Kubefile .
    
    popd > /dev/null

    # 4. 推送镜像
    echo "    正在推送 ($ARCH)..."
    sealos push "$IMG_TAG" "$IMG_DEST"

    # 5. 清理 builddir
    echo "    清理临时目录 $BUILD_DIR ..."
    rm -rf "$BUILD_DIR"
}

# --- 3. 执行构建与推送 ---
echo -e "\033[1;33m==> [2/4] 构建 AMD64 架构...\033[0m"
build_image_arch "amd64" "$IMG_AMD64" "$TARGET_AMD64"

echo -e "\033[1;33m==> [3/4] 构建 ARM64 架构...\033[0m"
build_image_arch "arm64" "$IMG_ARM64" "$TARGET_ARM64"

# --- 4. 合并 Manifest 并推送 ---
echo -e "\033[1;33m==> [4/4] 创建并推送 Manifest List...\033[0m"

# 清理旧 Manifest
sealos rmi "$IMAGE_NAME_FULL" 2>/dev/null || true

# 创建 Manifest
sealos manifest create "$IMAGE_NAME_FULL"

# 添加分架构镜像 (引用远程 docker:// 地址)
sealos manifest add "$IMAGE_NAME_FULL" "$TARGET_AMD64"
sealos manifest add "$IMAGE_NAME_FULL" "$TARGET_ARM64"

# 检查
sealos manifest inspect "$IMAGE_NAME_FULL"

# 推送 Manifest
sealos manifest push --all "$IMAGE_NAME_FULL" "$TARGET_FULL"

# 清理本地 Manifest 缓存 (可选)
sealos rmi "$IMAGE_NAME_FULL" 2>/dev/null || true

echo -e "\033[0;32mSUCCESS! 镜像发布完成。\033[0m"
echo -e "镜像地址: ${IMAGE_NAME_FULL}"
